<?php

namespace App\Models\User;

use App\Http\Config\WechatAPI;
use App\Library\Tools;
use App\Models\Admin\AdminUser;
use App\Models\Company;
use App\Models\Wechat;
use Illuminate\Database\Eloquent\Model;

class UserWechat extends Model
{
    static $object;

    /**
     * @return UserWechat
     */
    public static function getInstance(){
        if(empty(self::$object)){
            self::$object = new self();
        }
        return self::$object;
    }

    // 创建部门
    public function addDepartment($name, $parentId, &$errMsg = null){
        $token = Wechat::getInstance()->getToken();
        $url = WechatAPI::$qywx_conf['department_create']."?access_token={$token}";
        $res = Tools::curl($url, json_encode(["name" => $name, "parentid" => $parentId], JSON_UNESCAPED_UNICODE));
        $res = json_decode($res, true);
        if(isset($res['errcode']) && $res['errcode'] == 0 && !empty($res['id'])){
            return $res['id'];
        }else{
            $errMsg = "企业微信消息：".(isset(WechatAPI::$qyWx_msg[$res['errcode']]) ? WechatAPI::$qyWx_msg[$res['errcode']] : $res['errmsg']);
            return false;
        }
    }

    // 更新部门
    public function updateDepartment($id, $departmentId = 1, &$errMsg = null){
//        $oldDepartmentId = empty($oldDepartmentId) ? 1 : $oldDepartmentId;
//        $userList = $this->getDepartmentUserList($oldDepartmentId, $errMsg);
//        $temp = [];
//        if($userList && is_array($userList)){
//            foreach ($userList as &$item){
//                $key = array_search($oldDepartmentId, $item['department']);
//                if($key !== false && $key !== null){
//                    $item['department'][$key] = $departmentId;
//                    $res = $this->updateQYUser($item['userid'], $item);
//                    if(!isset($res['errcode']) || $res['errcode'] != 0){
//                        $errMsg = "企业微信消息：".(isset(WechatAPI::$qyWx_msg[$res['errcode']]) ? WechatAPI::$qyWx_msg[$res['errcode']] : $res['errmsg']);
//                        return false;
//                    }
//                }
//            }
//        }
        $userData = AdminUser::query()->from(AdminUser::query()->getModel()->getTable()." as u")
            ->leftJoin(Company::query()->getModel()->getTable()." as c", "u.company_id", "=", "c.id")
            ->where(["c.id" => $id, "u.mall_id" => request()->mallData['id']])
            ->select("u.wechat_id", "u.id")
            ->get()->toArray();
        foreach ($userData as $item){
            $qyUserData = Wechat::getInstance()->buildQYUserWechat(["userid" => $item['wechat_id']], "get");
            if ($qyUserData['errcode'] == 0) {
                $user['main_department'] = $qyUserData['main_department'];
//                $wechatId = 0;
//                do {
                    $user["department"] = [$departmentId];
                    $res = $this->updateQYUser($item['wechat_id'], $user);
//                } while ($res['errcode'] == '40066' && !$wechatId && $wechatId = 1);
                if ($res['errcode'] != 0) {
                    $errMsg = "企业微信消息：" . (isset(WechatAPI::$qyWx_msg[$res['errcode']]) ? WechatAPI::$qyWx_msg[$res['errcode']] : $res['errmsg']);
                    return false;
                }
            }
        }
        return true;
    }

    /* 获取部门成员 */
    public function getDepartmentUserList($departmentId, &$errMsg = null, $fetch_child = false){
        $token = Wechat::getInstance()->getToken();
        $oldData = @json_decode(file_get_contents(
            WechatAPI::$qywx_conf['user_simplelist']."?access_token={$token}&department_id={$departmentId}&fetch_child=".($fetch_child ? 1 : 0)
        ), true);
        if(!isset($oldData['errcode']) || $oldData['errcode'] != 0){
            $errMsg = "企业微信消息：".(isset(WechatAPI::$qyWx_msg[$oldData['errcode']]) ? WechatAPI::$qyWx_msg[$oldData['errcode']] : $oldData['errmsg']);
            return false;
        }
        return $oldData['userlist'];
    }

    /* 删除部门 */
    public function delDepartment($departmentId, &$errMsg = null){
        $token = Wechat::getInstance()->getToken();
        $oldData = @json_decode(file_get_contents(WechatAPI::$qywx_conf['department_del']."?access_token={$token}&id={$departmentId}"), true);
        if(!isset($oldData['errcode']) || !in_array($oldData['errcode'], [0, 60123])){
            $errMsg = "企业微信消息：".(isset(WechatAPI::$qyWx_msg[$oldData['errcode']]) ? WechatAPI::$qyWx_msg[$oldData['errcode']] : $oldData['errmsg']);
            return false;
        }
        return true;
    }

    // 创建企业微信用户并邀请
    public function createQYUser($userData, $companyId = 0, $wechatId = 0)
    {
        if($companyId) {
            $companyData = Company::query()->where("id", $companyId)->select('wechat_channel_id')->first();
            if (empty($companyData)) {
                throw new \Exception("部门不存在");
            }
            $companyData = $companyData->toArray();
            $companyData['wechat_channel_id'] = empty($companyData['wechat_channel_id']) ? 1 : $companyData['wechat_channel_id'];
        }else{
            $companyData = ['wechat_channel_id' => $wechatId];
        }
        $data = array(
            'userid' => $userData['wechat_id'],
            'name' => $userData['name'],
            'mobile' => $userData['mobile'],
            'department' => [intval($companyData['wechat_channel_id'])],
            'position' => $userData['position'],
            'gender' => $userData['sex'] == '女'? '2' : '1',
            'email' => $userData['email']
        );
        $result = Wechat::getInstance()->buildQYUserWechat($data,'create');
        if($result['errcode'] != 0){
            if($result['errcode'] == '40066' && $wechatId == 0){
                return $this->createQYUser($userData, 0, 1);
            }
            throw new \Exception("企业微信消息：".(isset(WechatAPI::$qyWx_msg[$result['errcode']]) ? WechatAPI::$qyWx_msg[$result['errcode']] : $result['errmsg']));
        }
        return true;
    }

    public function updateQYUser($userId, $userData)
    {
        $requestParam = ["userid" => $userId];
        if(!empty($userData['name'])){
            $requestParam['name'] = $userData['name'];
        }
        if(!empty($userData['mobile'])){
            $requestParam['mobile'] = $userData['mobile'];
        }
        if(!empty($userData['position'])){
            $requestParam['position'] = $userData['position'];
        }
        if(!empty($userData['sex'])){
            $requestParam['gender'] = $userData['sex'] == '女'? 2 : 1;
        }
        if(isset($userData['status'])){
            $requestParam['enable'] = $userData['status'] == 1 ? 0 : 1;
        }
        if(!empty($userData['wechat_channel_id'])){
            $requestParam['department'] = [$userData['wechat_channel_id']];
        }
        if(!empty($userData['department']) && is_array($userData['department'])){
            $requestParam['department'] = $userData['department'];
        }
        if(!empty($userData['main_department'])){
            $requestParam['main_department'] = $userData['main_department'];
        }
        if(!empty($userData['email'])){
            $requestParam['email'] = $userData['email'];
        }
        return Wechat::getInstance()->buildQYUserWechat($requestParam,'update');
    }

    public function deleteQYUser($wechat_id)
    {
        $data = ['userid' => $wechat_id];
        try {
            Wechat::getInstance()->buildQYUserWechat($data, 'delete');
        }catch (\Exception $e){}
        return true;
    }

}
